﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace IntegrationPlatformMappingTool
{
    public class XmlHelper
    {
        /// <summary>
        /// Parses a work item type definition file to retrieve all fields
        /// </summary>
        /// <param name="filepath">The fully qualified path to the WITD file</param>
        /// <param name="workitemtype">This is the name of the work item type returned as an out param</param>
        /// <returns>A sorted list of all of the fields from the WITD</returns>
        public static SortedList<string, Field> GetFields(string filepath, out string workitemtype)
        {
            SortedList<string, Field> fields = new SortedList<string, Field>();

            XmlDocument x = new XmlDocument();
            x.Load(filepath);
            fields = ReadData(x, out workitemtype);

            return fields;
        }

        public static SortedList<string, Field> ReadData(XmlDocument x, out string workitemtype)
        {
            SortedList<string, Field> fields = new SortedList<string, Field>();

            XmlNodeList nodes = x.SelectNodes("//WORKITEMTYPE/FIELDS/FIELD");
            XmlNode titleNode = x.SelectSingleNode("//WORKITEMTYPE");

            workitemtype = titleNode.Attributes["name"].Value.ToString();

            for (int i = 0; i < nodes.Count; i++)
            {
                Field f = new Field()
                {
                    Name = nodes[i].Attributes["name"].Value,
                    ReferenceName = nodes[i].Attributes["refname"].Value,
                    DataType = nodes[i].Attributes["type"].Value
                };
                fields.Add(f.Name, f);
            }

            return fields;
        }
    }
}